import sys
import os
import logging
import re
import json
from typing import Dict, List, Any, Optional, Tuple

# 添加项目根路径到 sys.path
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))

# 导入 MySQLUtil
from shared.utils.MySQLUtil import MySQLUtil

# 设置日志
logger = logging.getLogger(__name__)

def get_留学录取结果满意度(
    project_id: int,
    questionnaire_ids: List[int],
    product_code: Optional[str] = None,
    project_code: Optional[str] = None,
    region_code: Optional[str] = None
) -> Dict[str, Any]:
    """
    留学录取结果满意度 - 指标计算函数
    
    ## 指标说明
    该指标用于衡量学生对留学录取结果的满意程度，通过问卷收集学生对录取结果的评价，
    计算各选项（很满意、满意、基本满意、不满意、很不满意）的占比情况。
    指标数据来源于问卷问题T00000661的答案统计，不包含"无法评价"选项。
    
    ## Args
        project_id (int): 项目ID，用于查询项目配置信息
        questionnaire_ids (List[int]): 问卷ID集合，用于确定数据范围
        product_code (Optional[str]): 产品编码，用于路由到特定计算逻辑
        project_code (Optional[str]): 项目编码，用于路由到特定计算逻辑
        region_code (Optional[str]): 区域编码，用于路由到特定计算逻辑
        
    ## 示例
    ### 输入
    ```json
    {
        "project_id": 6768,
        "questionnaire_ids": [12709, 12710]
    }
    ```
    
    ### 输出
    ```json
    {
        "success": true,
        "message": "ok",
        "code": 0,
        "result": [
            {
                "calcVals": [
                    {
                        "val": [
                            {"key": "很满意", "val": "0.146059"},
                            {"key": "满意", "val": "0.141016"},
                            {"key": "基本满意", "val": "0.139148"},
                            {"key": "不满意", "val": "0.145499"},
                            {"key": "很不满意", "val": "0.133171"}
                        ]
                    }
                ]
            }
        ]
    }
    ```
    """
    logger.info(f"开始计算指标: 留学录取结果满意度, 项目ID: {project_id}")
    
    try:
        db = MySQLUtil()  

        # 1. 查询项目配置信息
        project_sql = """
        SELECT client_code, item_year, dy_target_items, split_tb_paper 
        FROM client_item 
        WHERE id = %s
        """
        project_info = db.fetchone(project_sql, (project_id,))
        if not project_info:
            raise ValueError(f"未找到项目ID={project_id}的配置信息")

        client_code = project_info['client_code']
        item_year = project_info['item_year']
        split_tb_paper = project_info['split_tb_paper']
        
        logger.info(f"项目配置: client_code={client_code}, item_year={item_year}, split_tb_paper={split_tb_paper}")

        # 2. 查询问卷信息
        questionnaire_sql = f"""
        SELECT id, dy_target 
        FROM wt_template_customer 
        WHERE id IN ({','.join(['%s'] * len(questionnaire_ids))})
        """
        questionnaires = db.fetchall(questionnaire_sql, tuple(questionnaire_ids))
        if not questionnaires:
            raise ValueError(f"未找到问卷ID集合={questionnaire_ids}的配置信息")
        
        logger.info(f"查询到问卷信息: {questionnaires}")

        # 3. 过滤GRADUATE_SHORT调研对象的问卷
        valid_questionnaire_ids = [q['id'] for q in questionnaires if q['dy_target'] == 'GRADUATE_SHORT']
        if not valid_questionnaire_ids:
            raise ValueError("未找到目标调研对象(GRADUATE_SHORT)的问卷ID")
            
        logger.info(f"找到有效问卷ID: {valid_questionnaire_ids}")

        # 4. 查询问题信息
        question_sql = """
        SELECT id, wt_code, wt_obj 
        FROM wt_template_question_customer 
        WHERE cd_template_id = %s AND wt_code = %s AND is_del = 0
        """
        question_info = db.fetchone(question_sql, (valid_questionnaire_ids[0], 'T00000661'))
        if not question_info:
            raise ValueError("未找到指定问题编码(T00000661)的问题信息")
            
        logger.info(f"找到问题信息: {question_info['id']}")

        # 5. 解析问题选项
        wt_obj = json.loads(question_info['wt_obj'])
        options = []
        for item in wt_obj['itemList']:
            if item['key'] != '6':  # 排除"无法评价"选项
                options.append({
                    'key': item['val'],
                    'val': None  # 将在后续计算中填充
                })

        # 6. 计算答案占比
        answer_table = f"re_dy_paper_answer_{split_tb_paper}"
        ratio_sql = f"""
        SELECT
            sum(c1)/(sum(c1)+sum(c2)+sum(c3)+sum(c4)+sum(c5)) AS ratio_c1,
            sum(c2)/(sum(c1)+sum(c2)+sum(c3)+sum(c4)+sum(c5)) AS ratio_c2,
            sum(c3)/(sum(c1)+sum(c2)+sum(c3)+sum(c4)+sum(c5)) AS ratio_c3,
            sum(c4)/(sum(c1)+sum(c2)+sum(c3)+sum(c4)+sum(c5)) AS ratio_c4,
            sum(c5)/(sum(c1)+sum(c2)+sum(c3)+sum(c4)+sum(c5)) AS ratio_c5
        FROM
            {answer_table}
        WHERE
            cd_template_id = %s
            AND wid = %s
            AND ans_true = 1
        """
        ratio_result = db.fetchone(ratio_sql, (valid_questionnaire_ids[0], question_info['id']))
        if not ratio_result:
            raise ValueError("未找到有效的答案数据")

        # 7. 填充选项值
        ratios = [ratio_result[f'ratio_c{i+1}'] for i in range(5)]
        for i, option in enumerate(options):
            option['val'] = f"{float(ratios[i]):.6f}" if ratios[i] else "0.000000"

        logger.info(f"指标 '留学录取结果满意度' 计算成功")
        return {
            "success": True,
            "message": "ok",
            "code": 0,
            "result": [{
                "calcVals": [{
                    "val": options
                }]
            }]
        }

    except Exception as e:
        logger.error(f"计算指标 '留学录取结果满意度' 时发生错误: {str(e)}", exc_info=True)
        return {
            "success": False,
            "message": f"数据获取失败: 留学录取结果满意度",
            "code": 500,
            "error": str(e)
        }